package cc.ufinity.networkdiagnose.widget;

import java.lang.reflect.Field;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.net.wifi.WifiInfo;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.manager.FTPConfig;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.NetworkManager;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.WlanManager;
import cc.ufinity.networkdiagnose.util.StringUtils;
import cc.ufinity.networkdiagnose.view.R;

public class RoamTestWidgetProxy extends GeneralTestWidget {
    private WlanManager wlanManager;
    private NetworkManager nm;
    private Activity ctx;
    private Handler handlerChild;
    private Handler handler;
    private Button btnback;
    private Button btnStart; 
    private boolean processing;
    private EditText ipEt;
    //private EditText frequencyEt;
    //private EditText byteEt;
    private int current;
    private int successTimes;
    private int roamTimes = 0;
    private int frequency;
    private Task task;
    private static String testIp;
    private static String frequencyTest;
    private static String byteTest;
    public static int testFlag = 0;
    public static int taskFlag = 0;   
    private String currentMac = "";
    private String orignMac = "";
    private String pingMac = "";
    private String priorMac = "";
    private boolean isRoamSucceed = false;
    
	private boolean isFirst = true;
	private boolean isPingSuccess = false;
	
    public RoamTestWidgetProxy(Activity context, Handler handl) {
        super(context);
        this.ctx = context;
        this.handlerChild = handl;
        wlanManager = new WlanManager(ctx);
        inflate(context, R.layout.roam_ping_proxy, this);
        btnback = (Button) this.findViewById(R.id.roam_test_proxy_btnback);
        btnStart = (Button) this.findViewById(R.id.btn_roam_proxy_start); 
        ipEt = (EditText) this.findViewById(R.id.roamEditTextProxy);
        //frequencyEt = (EditText) this.findViewById(R.id.roamFrequencyEditTextProxy);
        //byteEt = (EditText) this.findViewById(R.id.roambyteEditTextProxy);
        handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case MessageWhat.DO_NEXT_TEST:
            		//mSendBroadcast(ctx);
            		handlerSendToTarget(handlerChild, MessageWhat.HANDLER_ROAM);
                   // showNextText();
                    break;
                default:
                    update(msg.what);
                }
            }
        };
        btnback.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                backToTask(ctx);
            }
        });

        btnStart.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                start();
            }
        });
        //wlanManager.setHandler(handler);
        nm = new NetworkManager();
        nm.setHandler(handler);
        task = (Task)ctx.getIntent().getSerializableExtra(TAG_REFER_TASK); 
        System.err.println(task.acIp+"===================================ROAM=======================");
        //inputUserPassDialog() ;

	    testIp = "www.baidu.com";  
	    frequencyTest = "50";  
	    byteTest = "100";  
        start();
    } 
    /**
     * 配置测试IP
     * @param ctx
     * @param wlanManager
     * @param handler
     */
    public void inputUserPassDialog1() {
    	LayoutInflater factory = LayoutInflater.from(ctx);
		final View dialogView = factory.inflate(R.layout.roam_ping_input_info_dialog, null);
		final EditText ipText = (EditText) dialogView.findViewById(R.id.roamEditTextProxy);  
		final EditText frequencyText = (EditText) dialogView.findViewById(R.id.roamFrequencyEditTextProxy);  
		final EditText byteText = (EditText) dialogView.findViewById(R.id.roambyteEditTextProxy);  
        String ip = task.acIp==null?"": task.acIp;
        if(ip.length()>4 && ip.lastIndexOf(".")>0)
        	ip = ip.substring(0,ip.lastIndexOf(".")+1);
        ipText.setText(ip);
        ipText.setSelection(ip.length());
        frequencyText.setText("100");
        byteText.setText("100");
        AlertDialog.Builder builder = new AlertDialog.Builder(ctx); 
        builder.setTitle("漫游测试选项配置"); 
        builder.setView(dialogView); 
        builder.setCancelable(false); 
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
         	public void onClick(DialogInterface dialog, int id) {
	       		 testIp = ipText.getText().toString();  
	       		 frequencyTest = frequencyText.getText().toString();  
	       		 byteTest = byteText.getText().toString();  
	       		 System.err.println(testIp+":======================"+frequency+":==================="+byteTest);
	    		 try { 
	    			 Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
					 field.setAccessible(true);
	    			 if (StringUtils.isEmpty(testIp)) {
						field.set(dialog, false);
						showMessage(ctx, "请输入测试IP");
					 }else if (!StringUtils.isIPV4(testIp)) { 
						    field.set(dialog, false);
			    			showMessage(ctx, "请输入正确的IPV4地址!");
					 }else if (StringUtils.isEmpty(frequencyTest)) { 
						    field.set(dialog, false);
			    			showMessage(ctx, "请输入测试次数!");
					 }else if (StringUtils.isEmpty(byteTest)) { 
						    field.set(dialog, false);
			    			showMessage(ctx, "请输入测试数据包大小!");
					 }else{ 
						 field.set(dialog, true);  
						 start();
					 }
	    		 } catch (Exception e) {
						e.printStackTrace();
						showMessage(ctx, "配置失败，请稍后重试");
				 }
        	}
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener(){
        	public void onClick(DialogInterface dialog, int id) {
        		try {
					Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
					field.setAccessible(true);
					field.set(dialog, true);
				} catch (Exception e) {
					e.printStackTrace();
				}
				GlobalApp.result_ROAM_test=new StringBuffer("\n\n漫游测试项已取消");
        		//mSendBroadcast(ctx);
        		handlerSendToTarget(handlerChild, MessageWhat.HANDLER_ROAM);
        		dialog.cancel();
        	}
        });
	 	wifiListDialog = builder.create();
	    wifiListDialog.show();  
    }
  
    private void doNextTest() {
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                sendMsg(MessageWhat.DO_NEXT_TEST, handler);
            }
        };
        Timer t = new Timer();
        t.schedule(timerTask, TASK_PERFORM_INTERVAL);
       // this.showMessage(ctx, "漫游认证测试已完成，10秒后进入下一环节.");
    }

    public void update(int what) {
    	//----------------------------------------------------------
		if(isFirst) {
			isFirst = false;
			StringBuffer temp = new StringBuffer();
			GlobalApp.result_ROAM_test = temp;
		}
	//----------------------------------------------------------
        this.setDialogProgress(current); 
        StringBuffer s = null;
        switch (what) {
        case MessageWhat.PING_SUCCESS: 
        	isPingSuccess = true;
          //----------------------------------------------------------
			
			GlobalApp.result_ROAM_test.append(nm.getPingResult());
		
	//---------------------------------------------------------- 
         //   successTimes++;
            break;
        case MessageWhat.ROAM_SUCCESS: 
        	orignMac = pingMac;
        	isRoamSucceed = true;
			GlobalApp.result_ROAM_test.append(nm.getPingResult()); 
            successTimes++;
            break;
        case MessageWhat.PING_FAILED:
        	isPingSuccess = false;
            s = new StringBuffer();
            s.append("第").append(current).append("次测试失败");
			GlobalApp.result_ROAM_test.append("第").append(current).append("次测试失败\n"); 
            break;
        case MessageWhat.ROAM_FAILED:
            s = new StringBuffer();
            s.append("第").append(current).append("次测试失败");
			GlobalApp.result_ROAM_test.append("第").append(current).append("次测试失败\n"); 
            break;
        }
        if (current == frequency) {
            s = new StringBuffer();
            s.append("漫游测试次数：").append(roamTimes);
            s.append(";成功次数：").append(successTimes).append('\n');
            float tempRate = roamTimes==0?0:(float) successTimes / roamTimes * 100;
            s.append("漫游测试成功率：").append(tempRate).append('%');
          //----------------------------------------------------------
			
			GlobalApp.result_ROAM_test.append("\n漫游测试次数：").append(roamTimes)
					.append("\n成功次数：").append(successTimes)
					.append("\n漫游测试成功率：").append(tempRate).append("%\n");

		//---------------------------------------------------------- 

            /*if(successTimes > task.testCount) {
            	successTimes = task.testCount;
            }*/
            task.userRoamSuccessRate = String.valueOf(tempRate);
            
            task.userRoamCount = roamTimes + "";
            task.userRoamSuccessCount = successTimes +"";
            

System.out.println("task.userRoamCount => " + task.userRoamCount);
System.out.println("task.userRoamSuccessCount => " + task.userRoamSuccessCount);
System.out.println("task.userRoamSuccessRate => " + task.userRoamSuccessRate);
            
            ctx.getIntent().putExtra(TAG_REFER_TASK, task);
            
            this.dismissProgressDialog();
            doNextTest();
        } 
        processing = false;
    }

    private void start() {
        processing = false;
        current = 0;
        successTimes = 0; 
        WifiInfo wifiInfo = wlanManager.getCurrentNetwork();
        if(wifiInfo!=null) {
        	orignMac = wifiInfo.getBSSID();
        	priorMac = wifiInfo.getBSSID();
        }
        final FTPConfig ftp = this.getFTPConfig(ctx);
        if (ftp!=null && ftp.userName!=null && ftp.userName.length() > 0) {
            final String ip = ipEt.getText().toString();
          //  frequency = StringUtils.parseInt(frequencyEt.getText().toString());
            frequencyTest = frequencyTest==null?"1":frequencyTest;
            frequency = StringUtils.parseInt(frequencyTest);
            //final int bytes = StringUtils.parseInt(byteEt.getText().toString());
            byteTest = byteTest==null?"1":byteTest;
            final int bytes = StringUtils.parseInt(byteTest);
      		 System.err.println(frequencyTest+":$$$$$$$$$$$$$$$$$$$$$$"+frequency+":$$$$$$$$$$$$$$$$$$"+bytes);
        //    if (StringUtils.isIPV4(ip)) {
              //  this.showProgressDialog(ctx, "正在进行漫游测试...", frequency);
                new Thread() {
                    public void run() {
                        while (current < frequency) {
                            if (!processing) {
                                processing = true;
                                current++;
//                                nm.ping(ip, 1, bytes);
                                WifiInfo wifiInfo = wlanManager.getCurrentNetwork();
                                if(wifiInfo!=null) {
                                	currentMac = wifiInfo.getBSSID();
                                	if(priorMac!=null && !priorMac.equals(currentMac)) {
                                		priorMac = currentMac;
                                		roamTimes ++;
                                	}
                                }
                                if(currentMac!=null && orignMac!=null && !currentMac.equals(orignMac)) {
                                	if(isRoamSucceed) {
                                		System.out.println("-----漫游测试  无休眠【1】...");
                                		isRoamSucceed = false;
                                		nm.ping(ip, 1, bytes);
                                	} else {
                                    	pingMac = currentMac;
    	                            	 try {
    	                            		 System.out.println("-----漫游测试  休眠 3 秒中...");
    	                                     Thread.sleep(3000);
    	                                 } catch (InterruptedException e) { }
                                    	nm.pingForRoam(ip, 1, bytes);
                                	}
                                } else {
                                	isRoamSucceed = false;
                                	if(isPingSuccess) {
                                		try {
	   	                                     Thread.sleep(1000);
	   	                                 } catch (InterruptedException e) { }
                                	}
                                    nm.ping(ip, 1, bytes);
								}
                            }
                        }
                    }
                }.start();
           /* } else {
                this.showMessage(ctx, "请输入正确的IPV4地址!");
            }*/
        }
    }
 

}
